<?php
declare (strict_types=1);

namespace app\middleware;

use app\service\AuthService;
use app\model\Admin;
use app\service\RedisService;
use app\service\TokenService;

class TokenCheck
{
    /**
     * @param $request
     * @param \Closure $next
     * @return mixed|\think\response\Json
     */
    public function handle($request, \Closure $next)
    {
        $header_token = $request->header('token');

        if (!$header_token) {
            return JsonData(9999, "token不能为空");
        }

        $res = explode('_', $header_token);

        $token = $res[0];
        $user_id = $res[1];

        $TokenService = new TokenService();
        $admin = $TokenService->getAdminByToken($user_id, $token);

        if (!$admin) {
            return JsonData(9999, "token错误");
        }

        AuthService::setUser($admin);

        if (!$TokenService->checkVaildTime($user_id, $token)) {
            return JsonData(9999, "token过期");
        }

        return $next($request);
    }
}
